package com.godenwater.recv.server.yanyu;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.godenwater.yanyu.IMessage;
import com.godenwater.yanyu.IMessageBody;
import com.godenwater.yanyu.IMessageHeader;
import com.godenwater.yanyu.utils.ByteUtil;
 

/**
 * 数据编码器
 * 
 * @ClassName: HexDataEncoder
 * @Description: TODO
 * @author lipujun
 * @date Feb 22, 2013
 * 
 */
public class ServerDataEncoder extends ProtocolEncoderAdapter {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		
//session.getId()
		if (message instanceof IMessage) {
			logger.info("[编码报文] 下行编码报文...");
			// 获取消息体
			IMessage msg = (IMessage) message;
			IMessageHeader header = msg.getHeader();
			IMessageBody body = msg.getBody();

			// 构造缓冲区大小
			int capacity = header.getLength() + body.getLength() + 1 + 2;// 1表示结束标识位数


			// 开始写入数据
			IoBuffer buffer = IoBuffer.allocate(capacity, false); // 构造一个缓冲区
			buffer.setAutoExpand(true);
			buffer.put(header.getStartBit());
			buffer.put(header.getStationAddr());// 作为下行，遥测站地址在前，中心站地址在后
			buffer.put(header.getCenterAddr());
			buffer.put(header.getFuncCode());
			buffer.put(header.getBodySize());
			
			buffer.put(body.getContent()); // 构造内容
			buffer.put(msg.getEOF()); // 构造结束符
			buffer.put(msg.getCRC()); // 构造CRC校验码

			buffer.flip();
			out.write(buffer);
		} else if (message instanceof byte[]) {
			
			byte[] msg = (byte[]) message;
			
			logger.info("[编码报文] 下发召测报文..." + ByteUtil.toHexString(msg));
			
			int capacity = msg.length;
			IoBuffer buffer = IoBuffer.allocate(capacity, false); // 构造一个缓冲区
			buffer.setAutoExpand(true);
			buffer.put(msg);
			buffer.flip();
			out.write(buffer);
		} else {
			logger.info("[编码报文] 报文类型不正确，不做下发处理！" + message.toString());
		}
	}

}
